<template>
    <el-dialog 
        class="form_layout_lock simple_dialog_form"
        :title="title" 
        :visible="visible" 
        @close="handleDialogClose">
        
        <el-form 
            ref="simpledialogform" 
            :model="dialogFormData" 
            :rules="dialogRules" 
            :label-width="labelWidth" 
            class="container-form">


            <el-row class="form_item_row">
                <el-col 
                    class="form_item_col"
                    v-for="item in formatHideSearch" 
                    :key="item.key" 
                    :span="item.span">
                    
                    <el-form-item :label="item.name" :prop="item.key">
                        <!-- 输入框 -->
                        <template v-if="item.type === 'input'">
                            <el-input v-model="dialogFormData[`${ item.key }`]" :placeholder="item.placeholder || `请输入${ item.name }`"></el-input>
                        </template>

                        <!-- 输入框 -->
                        <template v-if="item.type === 'inputnumber'">
                            <el-input-number 
                                v-model="dialogFormData[`${ item.key }`]" 
                                :min="item.min || 1" 
                                :max="item.max || 100">
                            </el-input-number>
                        </template>

                        <!-- 下拉选 -->
                        <template v-if="item.type === 'select'">
                            <el-select v-model="dialogFormData[`${item.key}`]" :placeholder="item.placeholder || `请选择${item.name}`">
                                <el-option v-for="selectItem in item.childrenList" 
                                    :key="selectItem.key"
                                    :label="selectItem.name"
                                    :value="selectItem.key">
                                </el-option>
                            </el-select>
                        </template>

                        <!-- 多选框 -->
                        <template v-if="item.type === 'checkbox'">
                            <el-checkbox v-model="dialogFormData[`${item.key}`]"></el-checkbox>
                        </template>

                        <!-- 多选框组 -->
                        <template v-if="item.type === 'checkboxgroup'">
                            <el-checkbox-group v-model="dialogFormData[`${item.key}`]">
                                <el-checkbox 
                                    v-for="checkItem in item.childrenList" 
                                    :key="checkItem.key" 
                                    :label="checkItem.key" >
                                    {{ checkItem.name }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </template>

                        <!-- 单选框组 -->
                        <template v-if="item.type === 'radiogroup'">
                            <el-radio-group v-model="dialogFormData[`${item.key}`]">
                                <el-radio 
                                    v-for="checkItem in item.childrenList" 
                                    :key="checkItem.key" 
                                    :label="checkItem.key" >
                                    {{ checkItem.name }}
                                </el-radio>
                            </el-radio-group>
                        </template>

                        <!-- 开关 -->
                        <template v-if="item.type === 'switch'">
                            <el-switch v-model="dialogFormData[`${item.key}`]"></el-switch>
                        </template>

                        <!-- 时间选择器 -->
                        <template v-if="item.type === 'time'">
                            <el-time-picker 
                                v-model="dialogFormData[`${item.key}`]" 
                                placeholder="请选择时间"
                                :value-format="item.valueformat || 'HH:mm:SS'">
                            </el-time-picker>
                        </template>

                        <!-- 任意时间范围 -->
                        <template v-if="item.type === 'timerange'">
                            <el-time-picker
                                is-range
                                v-model="dialogFormData[`${item.key}`]"
                                range-separator="至"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                placeholder="选择时间范围"
                                :value-format="item.valueformat || 'HH:mm:SS'">
                            </el-time-picker>
                        </template>

                        <!-- 日期选择器 -->
                        <template v-if="item.type === 'date'">
                            <el-date-picker
                                type="date"
                                clearable
                                v-model="dialogFormData[`${item.key}`]"
                                :placeholder="'请选择日期'"
                                :value-format="item.valueformat || 'timestamp'">
                            </el-date-picker>
                        </template>

                        <!-- 日期范围选择器 -->
                        <template v-if="item.type === 'daterange'">
                            <el-date-picker
                                type="daterange"
                                clearable
                                v-model="dialogFormData[`${item.key}`]"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                :value-format="item.valueformat || 'timestamp'">
                            </el-date-picker>
                        </template>

                        <!-- 日期时间选择器 -->
                        <template v-if="item.type === 'datetime'">
                            <el-date-picker
                                type="datetime"
                                clearable
                                v-model="dialogFormData[`${item.key}`]"
                                placeholder="请选择日期"
                                :value-format="item.valueformat || 'timestamp'">
                            </el-date-picker>
                        </template>

                        <!-- 日期时间范围选择器 -->
                        <template v-if="item.type === 'datetimerange'">
                            <el-date-picker
                                type="datetimerange"
                                clearable
                                v-model="dialogFormData[`${item.key}`]"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                :value-format="item.valueformat || 'timestamp'">
                            </el-date-picker>
                        </template>
                    </el-form-item>
                </el-col>
            </el-row>
            
        </el-form>


        <div slot="footer">
            <el-button type="primary" @click="handleDialogCommit">确定</el-button>
            <el-button @click="handleDialogClose">取消</el-button>
        </div>

    </el-dialog>
</template>
<script>
    /**
     * 
     * 
     * 目的是为了那些没有复杂交互的单一弹出表单方便布局取值
     * 
     * 如果是那种含盖交互的那种表单还是自己独立制作一个
     * 
     * 
     */
    import { typeDefaultValue, typeDefaultSpan } from './util/dictionary'
    export default {
        name: 'ElementDialog',
        components: {},
        props: {
            title: {
                type: String,
                default: '操作框'
            },  

            visible: {
                type: Boolean,
                default: false
            },

            labelWidth: {
                type: String,
                default: '110px'
            },

            dialogFormProps: {
                type: Array,
                default: () => []
            },


            dialogRules: {
                type: Object,
                default: () => {}
            },
        },
        data() {
            return {
                dialogFormData: {},

                dialogResolve: null,

                waitForFormData: null
            }
        },
        computed: {
            formatHideSearch() {
                if(!this.dialogFormProps?.length) return []
                return this.dialogFormProps.map(item => {
                    const { type } = item
                    return Object.assign({
                        span: typeDefaultSpan[type]
                    }, item)
                })
            },
        },
        methods: {
            /**
             * 
             * data 是数据，新增的时候可以为 null
             * state 是状态，false 新增, true 是修改
             * 
             */
            async handleOperateDialog(data = null, state = false) {
                // 重置同步装置 埋下一个钉子
                this.resetDialogPromise()
                // 初始化默认参数和那些什么规则
                this.resetDialogDataAndRules(data, state)
                // 打开弹框
                await this.$nextTick()
                this.$emit('update:visible', true)
                await this.$nextTick()
                // 清空状态
                this.$refs['simpledialogform'].clearValidate()
            },

            resetDialogPromise(type = true) {
                try {
                    if (this.waitForFormData) {
                        this.dialogResolve({ state: false, message: '重复刷新', data: {} })
                        this.waitForFormData = null
                        this.dialogResolve = null
                    }
                    if (!type) return
                    this.waitForFormData = new Promise((resolve) => {
                        this.dialogResolve = resolve
                    })
                } catch (error) {
                    console.log('error', error)
                }
            },

            /**
             * 
             * 初始化参数和规则
             * 
             */
            resetDialogDataAndRules(defaultData, state) {
                const formatData = {}
                this.dialogFormProps.forEach(item => {
                    const { defaultValue, key, type } = item
                    // 如果传递了数据
                    if(state && defaultData[key]) {
                        formatData[`${ key }`] = defaultData[key]
                    } else {
                        if(defaultValue) {
                            formatData[`${ key }`] = defaultValue
                        } else {
                            // 根据类型的定义值
                            formatData[`${ key }`] = typeDefaultValue[type] || ''
                        }
                    }
                })
                this.dialogFormData = JSON.parse(JSON.stringify(formatData))
            },

            handleDialogClose() {
                if(this.waitForFormData !== null) {
                    if(this.dialogResolve !== null) {
                        this.dialogResolve({ state: false, message: '弹框关闭', data: {} })
                        this.dialogResolve = null
                    }
                    this.waitForFormData = null
                }
                this.$emit('update:visible', false)
            },

            handleDialogCommit() {
                this.$refs['simpledialogform'].validate(valid => {
                    // console.log('valid', valid)
                    if(!valid) return
                    const formatData = JSON.parse(JSON.stringify(this.dialogFormData)) 
                    console.log('formatData', formatData)
                    // 这里处理数据同步返回给页面
                    this.dialogResolve({ 
                        state: true, 
                        message: '数据获取成功', 
                        data: formatData
                    })
                })
            }
        },
        beforeCreate() {

        },
        created() {

        },
        beforeMount() {

        },
        mounted() {
            
        },
        beforeDestroy() {

        },
    }
</script>
<style lang="scss">
.simple_dialog_form {
    .form_item_row {
        display: flex;
        flex-wrap: wrap;
    }
}
</style>
<style lang="scss" scoped>

</style>